import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:path_provider/path_provider.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:raze/artifacts/helper_function.dart';
import 'package:raze/artifacts/notifier_glimmer.dart';
import 'package:raze/artifacts/username_edit_dialog.dart';
import 'package:raze/lore/chronicle/user_chronicle.dart';
import 'package:raze/lore/glyph/user_essence.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 设置页面
class SettingsRealms extends StatefulWidget {
  const SettingsRealms({super.key});

  @override
  State<SettingsRealms> createState() => _SettingsRealmsState();
}

class _SettingsRealmsState extends State<SettingsRealms> {
  @override
  Widget build(BuildContext context) {
    final userChronicle = Get.find<UserChronicle>();

    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/background.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SafeArea(
          child: Obx(() {
            final currentUser = userChronicle.currentUser;

            if (currentUser == null) {
              return Center(
                child:
                    Text('Please login first')
                        .applyTypeSize(16.sp)
                        .applyTypeColor(RazeConstants.black)
                        .applyNotoSans(),
              );
            }

            return Column(
              children: [
                // 顶部导航栏
                _composeTopNavigationBar(),

                // 主要内容区域
                Expanded(
                  child: SingleChildScrollView(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      child: Column(
                        children: [
                          // 用户信息区域
                          _composeUserProfileSection(
                            currentUser,
                            userChronicle,
                          ),

                          40.h.boxHeight,

                          // 设置选项列表
                          _composeSettingsOptionsList(),

                          40.h.boxHeight,
                        ],
                      ),
                    ),
                  ),
                ),

                // 底部登出按钮
                _composeLogoutButton(userChronicle),
              ],
            );
          }),
        ),
      ),
    );
  }

  /// 组合顶部导航栏
  Widget _composeTopNavigationBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          Container(
                width: 30.w,
                height: 30.w,
                decoration: BoxDecoration(
                  color: RazeConstants.background,
                  borderRadius: BorderRadius.circular(8.r),
                  border: Border.all(color: RazeConstants.black, width: 1.5.w),
                ),
                child: Icon(
                  Icons.chevron_left_rounded,
                  size: 24.sp,
                  color: RazeConstants.black,
                ),
              )
              .withRightBottomShadow(thickness: 1)
              .withTouchResonance(onTap: () => Get.back()),
        ],
      ),
    );
  }

  /// 组合用户信息区域
  Widget _composeUserProfileSection(
    UserEssence currentUser,
    UserChronicle userChronicle,
  ) {
    return Column(
      children: [
        // 头像（带灰色蒙层和相机图标）
        GestureDetector(
          onTap: () => _handleAvatarSelection(userChronicle, currentUser),
          child: Container(
            width: 98.w,
            height: 98.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: RazeConstants.black, width: 2.w),
            ),
            child: ClipOval(
              child: Stack(
                fit: StackFit.expand,
                children: [
                  // 头像图片
                  currentUser.avatar.startsWith('/') ||
                          currentUser.avatar.contains('avatars')
                      ? Image.file(
                        File(currentUser.avatar),
                        width: 98.w,
                        height: 98.w,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return Image.asset(
                            'assets/images/avatar1.png',
                            width: 98.w,
                            height: 98.w,
                            fit: BoxFit.cover,
                          );
                        },
                      )
                      : Image.asset(
                        currentUser.avatar,
                        width: 98.w,
                        height: 98.w,
                        fit: BoxFit.cover,
                      ),
                  // 灰色蒙层
                  Container(color: RazeConstants.grey.withOpacity(0.5)),
                  // 相机图标（在蒙层中间）
                  Center(
                    child: Icon(
                      Icons.camera_alt_rounded,
                      size: 32.sp,
                      color: RazeConstants.white,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),

        16.h.boxHeight,

        // 用户名（带编辑图标）
        GestureDetector(
          onTap: () {
            UsernameEditDialog.revealUsernameEdit(
              initialUsername: currentUser.username,
              onUsernameUpdated: (newUsername) {
                final updatedUser = currentUser.copyWith(username: newUsername);
                userChronicle.updateCurrentUser(updatedUser);
                NotifierGlimmer.revealSuccess('Username updated successfully');
              },
            );
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(currentUser.username)
                  .applyTypeSize(20.sp)
                  .applyTypeColor(RazeConstants.black)
                  .applyBagelFatOne(weight: FontWeight.w400),
              6.w.boxWidth,
              Image.asset('assets/images/edit.png', width: 16.w, height: 16.w),
            ],
          ),
        ),
      ],
    );
  }

  /// 组合设置选项列表
  Widget _composeSettingsOptionsList() {
    return Column(
      children: [
        // Privacy Policy
        _composeSettingsItem(
          textColor: RazeConstants.black,
          title: 'Privacy Policy',
          onTap: () {
            HelperFunction.launchUrl(RazeConstants.privacyPolicyUrl);
          },
        ),
        12.h.boxHeight,

        // Terms Of Service
        _composeSettingsItem(
          textColor: RazeConstants.black,
          title: 'Terms Of Service',
          onTap: () {
            HelperFunction.launchUrl(RazeConstants.termsOfServiceUrl);
          },
        ),
        12.h.boxHeight,

        // Delete Account
        _composeSettingsItem(
          textColor: RazeConstants.red,
          title: 'Delete Account',
          onTap: () => _handleDeleteAccount(),
        ),
      ],
    );
  }

  /// 组合单个设置项
  Widget _composeSettingsItem({
    required String title,
    required Color textColor,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 14.h),
        decoration: BoxDecoration(
          color: RazeConstants.white,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(color: RazeConstants.black, width: 1.w),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(title)
                .applyTypeSize(16.sp)
                .applyTypeColor(textColor)
                .applyNotoSans(weight: FontWeight.w500),
            Icon(
              Icons.chevron_right_rounded,
              size: 20.sp,
              color: RazeConstants.black,
            ),
          ],
        ),
      ).withRightBottomShadow(thickness: 1),
    );
  }

  /// 组合登出按钮
  Widget _composeLogoutButton(UserChronicle userChronicle) {
    return Padding(
      padding: EdgeInsets.all(16.w),
      child: Container(
            width: double.infinity,
            height: 50.h,
            decoration: BoxDecoration(
              color: RazeConstants.blue,
              borderRadius: BorderRadius.circular(8.r),
              border: Border.all(color: RazeConstants.black, width: 2.w),
            ),
            child: Center(
              child: Text(
                'Log Out',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontFamily:
                      GoogleFonts.bagelFatOne(
                        fontWeight: FontWeight.w400,
                      ).fontFamily,
                  fontWeight: FontWeight.w400,
                  color: RazeConstants.white,
                  shadows: [
                    Shadow(offset: Offset(-1, -1), color: RazeConstants.black),
                    Shadow(offset: Offset(1, -1), color: RazeConstants.black),
                    Shadow(offset: Offset(1, 1), color: RazeConstants.black),
                    Shadow(offset: Offset(-1, 1), color: RazeConstants.black),
                  ],
                ),
              ),
            ),
          )
          .withRightBottomShadow(thickness: 1.5)
          .withTouchResonance(
            onTap: () {
              userChronicle.performLogout();
              // 提示
              NotifierGlimmer.revealSuccess('Log out successful.');
              // 返回主页
              Get.offAllNamed('/main');
            },
          ),
    );
  }

  /// 处理头像选择
  Future<void> _handleAvatarSelection(
    UserChronicle userChronicle,
    UserEssence currentUser,
  ) async {
    try {
      // 使用 wechat_assets_picker 选择图片
      final List<AssetEntity>? selectedAssets = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
          specialItemPosition: SpecialItemPosition.none,
        ),
      );

      if (selectedAssets == null || selectedAssets.isEmpty) {
        return;
      }

      final asset = selectedAssets.first;

      // 获取应用文档目录
      final appDocDir = await getApplicationDocumentsDirectory();
      final avatarDir = Directory('${appDocDir.path}/avatars');
      if (!await avatarDir.exists()) {
        await avatarDir.create(recursive: true);
      }

      // 获取图片文件
      final imageFile = await asset.originFile;
      if (imageFile == null) {
        NotifierGlimmer.revealInfo('Failed to load image file');
        return;
      }

      // 复制图片到本地目录
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final originalName = await asset.title;
      final extension = originalName?.split('.').last ?? 'png';
      final avatarFileName = 'avatar_${currentUser.id}_$timestamp.$extension';
      final avatarPath = '${avatarDir.path}/$avatarFileName';
      await imageFile.copy(avatarPath);

      // 更新用户头像
      final updatedUser = currentUser.copyWith(avatar: avatarPath);
      userChronicle.updateCurrentUser(updatedUser);
      NotifierGlimmer.revealSuccess('Avatar updated successfully');
    } catch (e) {
      NotifierGlimmer.revealInfo('Failed to select avatar: $e');
    }
  }

  /// 处理删除账号
  void _handleDeleteAccount() {
    Get.dialog(
      Dialog(
        backgroundColor: Colors.transparent,
        elevation: 0,
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 24.w),
          padding: EdgeInsets.all(24.w),
          decoration: BoxDecoration(
            color: RazeConstants.white,
            borderRadius: BorderRadius.circular(24.r),
            border: Border.all(color: RazeConstants.black, width: 2.w),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 标题
              Text('Delete Account')
                  .applyTypeSize(22.sp)
                  .applyTypeColor(RazeConstants.black)
                  .applyBagelFatOne(weight: FontWeight.w400),
              20.h.boxHeight,

              // 提示文本
              Text(
                    'Are you sure you want to delete your account? This action cannot be undone.',
                  )
                  .applyTypeSize(14.sp)
                  .applyTypeColor(RazeConstants.black)
                  .applyNotoSans()
                  .enshroudHorizontal(20.w),
              24.h.boxHeight,

              // 按钮区域
              Row(
                children: [
                  // 取消按钮
                  Expanded(
                    child: Container(
                          height: 50.h,
                          decoration: BoxDecoration(
                            color: RazeConstants.white,
                            borderRadius: BorderRadius.circular(16.r),
                            border: Border.all(
                              color: RazeConstants.black,
                              width: 2.w,
                            ),
                          ),
                          child: Center(
                            child: Text('Cancel')
                                .applyTypeSize(16.sp)
                                .applyTypeColor(RazeConstants.black)
                                .applyBagelFatOne(weight: FontWeight.w400),
                          ),
                        )
                        .withRightBottomShadow(thickness: 1.5)
                        .withTouchResonance(onTap: () => Get.back()),
                  ),
                  16.w.boxWidth,

                  // 确认按钮
                  Expanded(
                    child: Container(
                          height: 50.h,
                          decoration: BoxDecoration(
                            color: RazeConstants.red,
                            borderRadius: BorderRadius.circular(16.r),
                            border: Border.all(
                              color: RazeConstants.black,
                              width: 2.w,
                            ),
                          ),
                          child: Center(
                            child: Text('Delete')
                                .applyTypeSize(16.sp)
                                .applyTypeColor(RazeConstants.white)
                                .applyBagelFatOne(weight: FontWeight.w400),
                          ),
                        )
                        .withRightBottomShadow(thickness: 1.5)
                        .withTouchResonance(
                          onTap: () {
                            Get.back();
                            // 提示删除成功
                            NotifierGlimmer.revealSuccess(
                              'Account deleted successfully',
                            );
                            // 退出登录（实际逻辑）
                            final userChronicle = Get.find<UserChronicle>();
                            userChronicle.performLogout();
                            // 跳转到主页
                            Future.delayed(
                              const Duration(milliseconds: 500),
                              () {
                                Get.offAllNamed('/main');
                              },
                            );
                          },
                        ),
                  ),
                ],
              ),
            ],
          ),
        ).withRightBottomShadow(thickness: 2),
      ),
      barrierDismissible: true,
    );
  }
}
